
#include <algorithm>
#include <typeinfo>
#include <iostream>
#include <string>

class Any
{
public:
    Any() :_content(nullptr){}
    ~Any() {delete _content;}
    template <class T>
    T *get()
    {
        if(typeid(T) != _content->type()) return nullptr;
        return &((placeholder<T> *)_content)->_val;
    }
    template <class T>
    Any(const Any &any):_content(new placeholder<T>(any._content ? any._content->clone() : nullptr)) {}

    Any &operator=(const Any &any)
    {
        Any(any).swap(*this);
        return *this;
    }

    void swap(Any &any)
    {
        std::swap(_content,any._content);
    }
    template <class T>
    Any &operator=(const T &val)
    {
        Any(val).swap(*this);
        return *this;
    }

    template <class T>
    Any(const T &val): _content(new placeholder<T>(val)){}
private:
    class holder
    {
    public:
        virtual ~holder() {}
        virtual const std::type_info &type() = 0;
        virtual holder *clone() = 0;
    };

    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) :_val(val) {}
        virtual const std::type_info &type() {return typeid(T);}
        virtual holder *clone() {return new placeholder(_val);}
        T _val;
    };
    holder *_content;// 父类的指针，形成多态
};

class Test
{
public:
    Test() {std::cout << "构造函数" << std::endl;}
    ~Test() {std::cout << "析构函数" << std::endl;}
    Test(const Test &t) {std::cout << "拷贝" << std::endl;}
};

int main()
{
    Any a;
    {
        Test t;
        a = t;
    }




    a = 10;
    std::cout << *(a.get<int>()) << std::endl;

    a = std::string("你好!");
    std::cout << *(a.get<std::string>()) << std::endl;
    return 0;
}